<template>
  <div>
    <Modal
      class="model"
      v-model="model"
      @on-cancel="handleDrawerCancel('formValidate')"
      title="回访详细"
      :mask-closable="false"
      width="1000"
      draggable
    >
      <Row>
        <Col span="8" class="side-bg">
          <div class="basic">
            <h3>
              {{ patientuser.user_name }} {{ patientuser.age }}
              {{ genderfun(patientuser.gender) }}
            </h3>
            <h4 class="b-phone" style="width: 100%;">
              <span style="display: inline-block; width: 60px;">手机号：</span>
              <span
                v-if="patientuser.mobile"
                style="
                                    display: inline-block;
                                    width: calc(100% - 65px);
                                    overflow: hidden;
                                    white-space: nowrap;
                                    text-overflow: ellipsis;
                                "
                :title="patientuser.mobile"
                >{{ patientuser.mobile }}</span
              >
              <span v-else>--</span>
            </h4>
            <h4 class="b-phone" style="width: 100%;">
              <span style="display: inline-block; width: 60px;">微信号：</span>
              <span
                v-if="patientuser.wechat_id"
                style="
                                    display: inline-block;
                                    width: calc(100% - 65px);
                                    overflow: hidden;
                                    white-space: nowrap;
                                    text-overflow: ellipsis;
                                "
                :title="patientuser.wechat_id"
                >{{ patientuser.wechat_id }}</span
              >
              <span v-else>--</span>
            </h4>
          </div>
          <div class="sky-screen">
            <DatePicker
              :editable="false"
              type="daterange"
              v-model="datetime"
              placeholder="回访日期"
              @on-change="askData"
            >
            </DatePicker>
          </div>
          <Divider />
          <Timeline style="height: 380px; overflow: auto;">
            <TimelineItem v-for="item in list" :key="item.id">
              <p class="time">{{ item.created_at }}</p>
              <p class="content">{{ item.content }}</p>
              <p class="consultant">
                <span class="c-inr">{{ item.member_name }}</span>
                <Badge
                  status="processing"
                  :text="item.callback_status_name"
                  v-if="item.callback_status_name"
                  class="ivu-mr-8"
                />
                <Badge
                  class="ivu-mr-8"
                  status="warning"
                  v-if="item.callback_way_name"
                  :text="item.callback_way_name"
                />
              </p>
            </TimelineItem>
          </Timeline>
        </Col>
        <Col span="16">
          <div class="title">回访信息</div>
          <Divider />
          <Form
            :model="params"
            :label-width="118"
            class="return-form"
            :rules="ruleValidate"
            ref="formValidate"
          >
            <FormItem label="回访状态" prop="callback_state_id">
              <RadioGroup v-model="params.callback_state_id">
                <Radio
                  :label="item.value"
                  v-for="item in callbackstatus"
                  :key="item.value"
                  >{{ item.label }}
                </Radio>
              </RadioGroup>
            </FormItem>
            <FormItem label="回访方式" prop="callback_way_id">
              <RadioGroup v-model="params.callback_way_id">
                <Radio
                  :label="item.value"
                  v-for="item in callbackway"
                  :key="item.value"
                  >{{ item.label }}
                </Radio>
              </RadioGroup>
            </FormItem>
            <FormItem label="回访内容" prop="content">
              <Input
                v-model="params.content"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 5 }"
                placeholder="请输入回访内容"
              ></Input>
            </FormItem>
            <!-- <FormItem label="一级病种" prop="patient_diseases_id">
                        <Select v-model="params.patient_diseases_id" clearable placeholder="请选择" @on-change="changediseases(params.patient_diseases_id)">
                            <Option v-for="item in diseases" :value="item.value" :disabled="+item.status === 0"
                                    :key="item.value">{{ item.label }}</Option>
                        </Select>
                    </FormItem> -->
            <Row type="flex" :gutter="32">
              <Col span="12">
                <FormItem label="一级病种" prop="patient_diseases_id">
                  <Select
                    v-model="params.patient_diseases_id"
                    clearable
                    placeholder="请选择"
                    @on-change="changediseases(params.patient_diseases_id)"
                  >
                    <Option
                      v-for="item in diseases"
                      :value="item.value"
                      :disabled="+item.status === 0"
                      :key="item.value"
                      >{{ item.label }}</Option
                    >
                  </Select>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem
                  label="二级病种"
                  v-show="params.patient_diseases_id"
                  v-if="diseases_child.length > 0"
                  prop="patient_diseases_child_id"
                >
                  <Select
                    v-model="params.patient_diseases_child_id"
                    clearable
                    placeholder="请选择"
                  >
                    <Option
                      v-for="item in diseases_child"
                      :disabled="+item.status === 0"
                      :value="item.value"
                      :key="item.value"
                      >{{ item.label }}</Option
                    >
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <FormItem
              label="归属人"
              v-if="
                isPerson ||
                  (view_info.type === 1 &&
                    patientDetail.patient_data_type === '2')
              "
            >
              <Select v-model="params.belong_member_id" style="width: 190px;">
                <OptionGroup
                  :label="item.label"
                  v-for="item in member_list"
                  :key="item.value"
                >
                  <Option
                    v-for="items in item.children"
                    :value="items.value"
                    :key="items.value"
                    >{{ items.label }}</Option
                  >
                </OptionGroup>
              </Select>
            </FormItem>
            <!-- <FormItem label="标签" v-if="friendid&&bools&&state==0">
                        <Select v-model="params.tags_arr" filterable multiple>
                            <OptionGroup :label="item.tag_name" v-for="(item,index) in tagslist" :key="index">
                                <Option v-for="it in item.children" :disabled="item.isonline != 0" :value="`${item.wechatid}()${it.tag_id}()${it.tag_name}`" :key="it.tag_id">{{ it.tag_name }}
                                </Option>
                            </OptionGroup>
                        </Select>
                    </FormItem> -->
            <!-- <FormItem label="标签" v-else>
                        <Select v-model="params.tags_arr" filterable multiple disabled>
                            <OptionGroup :label="item.tag_name" v-for="(item,index) in tagslist" :key="index">
                                <Option v-for="it in item.children" :value="`${item.wechatid}()${it.tag_id}()${it.tag_name}`" :key="it.tag_id">{{ it.tag_name }}
                                </Option>
                            </OptionGroup>
                        </Select>
                    </FormItem> -->
            <FormItem label="患者状态">
              <Select
                v-model="params.patient_status_id"
                style="width: 190px;"
                @on-change="changeStatus"
                :disabled="IsSelect"
              >
                <Option
                  :value="item.value"
                  :disabled="+item.is_select === 0"
                  v-for="item in patientstatus"
                  :key="item.value"
                  >{{ item.label }}</Option
                >
              </Select>
            </FormItem>
            <!-- <FormItem label="视图切换" v-if="!isPerson && isCanChangeView && view_info.type !== 1"> -->
            <!-- <FormItem label="视图切换" v-if="!isPerson && view_info.type !== 1">
                        <Select v-model="params.move_id" style="width: 190px;" placeholder="请选择视图切换" clearable
                                >
                            <Option v-for="item in filterView" :value="item.value" :key="item.value">{{ item.title }}
                            </Option>
                        </Select>
                        <p>
                            <font color="#ed4014">输入视图名称，回车，可添加视图</font>
                        </p>
                    </FormItem> -->
            <FormItem
              v-if="+params.patient_status_id === 1"
              label="预到时间"
              prop="appointment_time"
            >
              <DatePicker
                :editable="false"
                type="date"
                :options="optionss"
                v-model="params.appointment_time"
                placeholder="请选择预到时间"
              ></DatePicker>
            </FormItem>
            <FormItem label="下次回访时间" prop="next_callback_time " v-if="+params.patient_status_id !== 3">
              <Row :gutter="16" type="flex">
                <Col>
                  <InputNumber
                    :formatter="$inputday"
                    :step="1"
                    v-model.number="DatePicker"
                    @on-change="blurday(DatePicker)"
                  >
                  </InputNumber>
                </Col>
                <Col>天后</Col>
                <Col>
                  <DatePicker
                    :editable="false"
                    :options="optionss"
                    type="date"
                    v-model="params.next_callback_time"
                    @on-change="changeday(params.next_callback_time)"
                    placeholder="请输入回访时间"
                  >
                  </DatePicker>
                </Col>
              </Row>
            </FormItem>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button @click="handleDrawerCancel('formValidate')">取消</Button>
        <Button
          type="primary"
          :loading="remarksloading"
          :disabled="disabled"
          @click="handleSubmit('formValidate')"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  callbackcallbackcommonlist,
  callbackcreate,
  customerwechattagslist,
  patientindexeditinfo,
  patientindexsearchchilddiseases,
} from "@/api/hqapi";
import { worktodowechatinfo } from "@api/hqapi/indextwo";
import { settingviewcreateview } from "@/api/hqapi/indexone";
import { mapState, mapMutations } from "vuex";
import util from "@/libs/util";
import dayjs from "dayjs";
export default {
  name: "returnVisit",
  props: {
    viewInfo: {
      type: Object,
      default: () => {},
    },
  },
  mounted() {},
  watch: {
    viewInfo: {
      handler(value) {
        if (value) this.view_info = value;
      },
      deep: true,
    },
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value) {
        callback();
      } else {
        callback(new Error("请选择下次回访时间"));
      }
    };
    const appointment_time = (rule, value, callback) => {
      if (value) {
        callback();
      } else {
        callback(new Error("请选择预到时间"));
      }
    };
    return {
      view_info: {},
      belongVIewId: "",
      isCanChangeView: true,
      member_list: [],
      isPerson: false,
      model: false,
      datetime: ["", ""],
      DatePicker: null,
      remarksloading: false,
      disabled: false,
      optionss: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 1000 * 24 * 3600;
        },
      },
      params: {
        move_id: "",
        patient_user_id: "",
        callback_state_id: "",
        callback_way_id: "",
        content: "",
        belong_member_id: "",
        patient_status_id: "",
        appointment_time: "",
        next_callback_time: "",
        tags_arr: [],
        patient_diseases_id: "",
        patient_diseases_child_id: "",
      },
      diseases: [],
      diseases_child: [],
      tags_arr: [],
      ruleValidate: {
        callback_state_id: [
          {
            required: true,
            message: "请选择回访状态",
            trigger: "change",
          },
        ],
        callback_way_id: [
          {
            required: true,
            message: "请选择回访方式",
            trigger: "change",
          },
        ],
        content: [
          {
            required: true,
            message: "请填写回访内容",
            trigger: "blur",
          },
        ],
        appointment_time: [
          {
            validator: appointment_time,
            trigger: "change",
          },
        ],
        next_callback_time: [
          {
            // required: true,
            // message: "请选择下次回访时间",
            validator: validatePass,
            trigger: "change",
          },
        ],
        patient_diseases_id: [
          {
            required: true,
            message: "请选择一级病种",
            trigger: "change",
          },
        ],
        patient_diseases_child_id: [
          {
            required: true,
            message: "请选择二级病种",
            trigger: "change",
          },
        ],
      },
      list: [],
      patientDetail: {},
      patientuser: [],
      callbackstatus: [],
      callbackway: [],
      patientstatus: [],
      tagslist: [],
      belongmemberid: "",
      filterView: [],
      IsSelect: false,
      friendid: "",
      state: "",
      bools: false,
    };
  },
  computed: {
    // filterView() {
    //     return this.tabList.length ? this.tabList.filter(ee => ee.type === "0") : []
    // }
    ...mapState("power/export", ["wsIsConnect"]),
  },
  // computed: {
  //     showBelong() {
  //         let path = this.$route.path;
  //         return path === "/business/publicList" || path === "/business/fishPond"
  //     }
  // },
  methods: {
    changeStatus() {
      this.$refs["formValidate"].fields.forEach((item) => {
        if (item.prop == "next_callback_time") {
          item.resetField();
          this.changeday(this.params.next_callback_time);
        }
      });
    },
    // askData (id) {
    //     callbackcallbackcommonlist({patient_user_id:id}).then(res=>{
    //         this.callbackstatus = res.callback_status
    //         this.callbackway = res.callback_way
    //         this.patientstatus = res.patient_status
    //         this.tagslist = res.tags_list
    //         this.params.tags = res.patient_tags_list.split(',')
    //         this.params.patient_status_id = res.patient_detail_list.patient_status_id
    //         this.params.appointment_time = res.patient_detail_list.appointment_time
    //         this.params.next_callback_time = res.patient_detail_list.next_callback_time
    //         this.DatePicker = res.patient_detail_list.date_count
    //     })
    // },

    askData() {
      this._patientindexeditinfo(this.params.patient_user_id);
      let path = this.$route.path;
      let isCheckView = 1;
      if (path === "/business/publicList" || path === "/business/fishPond") {
        this.isPerson = true;
        isCheckView = 0;
      }
      let config = {
        patient_user_id: this.params.patient_user_id,
        start_time: this.datetime[0],
        end_time: this.datetime[1],
        is_check_view: isCheckView,
        page: 0,
        pageSize: 0,
      };
      callbackcallbackcommonlist(config).then((res) => {
        let UnionId = util.cookies.get("uuid") ? util.cookies.get("uuid") : 0;
        this.bools = res.patient_detail_list.belong_member_id == UnionId;
        this.state = res.state;
        this.friendid = res.friendid;
        this.callbackstatus = res.callback_status;
        this.callbackway = res.callback_way;
        this.patientstatus = res.patient_status;
        this.IsSelect = res.can_select === 0;
        this.member_list = res.member_list;
        this.tagslist = res.tags_list;
        // let tags_array = []
        // for (let item of res.patient_tags_list) {
        //     for (let it of item.tags_arr) {
        //         tags_array.push(`${item.wechatid}()${it.tag_id}()${it.tag_name}`)
        //     }
        // }
        // this.params.tags_arr = JSON.parse(JSON.stringify(tags_array))
        // this.tags_arr = JSON.parse(JSON.stringify(tags_array))
        this.params.patient_status_id =
          res.patient_detail_list.patient_status_id;
        this.params.appointment_time = res.patient_detail_list.appointment_time;
        this.params.next_callback_time =
          res.patient_detail_list.next_callback_time;
        this.DatePicker = res.patient_detail_list.date_count || 0;
        this.patientuser = res.list.patient_user;
        this.patientuser.mobile = res.list.patient_user.mobile.join("/");
        this.filterView = res.view_list.map((ee) => {
          return {
            ...ee,
            value: ee.id,
            label: ee.title,
          };
        });
        this.params.move_id = res.view_info.view_id;
        this.isCanChangeView = res.view_info.view_id !== "";
        this.belongVIewId = res.view_info.view_id;
        this.list = res.list.list.list;
        this.belongmemberid = res.list.patient_user.belong_member_id;
      });
    },
    handleReturnVisit(id, row) {
      console.log(id, "row");
      if (row) {
        this.patientDetail = row;
      }
      (this.params = {
        patient_user_id: id,
        callback_state_id: "",
        callback_way_id: "",
        content: "",
        move_id: "",
        belong_member_id: "",
        patient_status_id: "",
        appointment_time: "",
        patient_diseases_id: "",
        patient_diseases_child_id: "",
        next_callback_time: "",
        tags_arr: [],
      }),
        this.askData();
      this.model = true;
    },
    // 获取病种
    _patientindexeditinfo(id) {
      patientindexeditinfo({ id: id }).then((res) => {
        this.params.patient_diseases_id = res.patient_diseases_id;
        this.params.patient_diseases_child_id =
          res.patient_diseases_child_id === "0"
            ? ""
            : res.patient_diseases_child_id;
        this.diseases = res.condition.diseases;
        this.diseases_child = res.condition.diseases_child;
      });
    },
    changediseases(pid) {
      patientindexsearchchilddiseases({
        pid: pid,
        patient_user_id: this.params.patient_user_id,
      }).then((res) => {
        this.diseases_child = res.list;
        this.params.patient_diseases_child_id = "";
      });
    },
    genderfun(type) {
      let gender = "";
      if (+type === 0) gender = "未知";
      else if (+type === 1) gender = "男";
      else if (+type === 2) gender = "女";
      return gender;
    },
    blurday(day) {
      this.$set(this.params, "next_callback_time", this.$blurday(day));
    },
    changeday(date) {
      this.DatePicker = this.$changeday(date);
    },
    handleDrawerCancel(name) {
      this.$refs[name].resetFields();
      this.model = false;
      this.params = {
        patient_user_id: "",
        callback_state_id: "",
        callback_way_id: "",
        content: "",
        belong_member_id: "",
        patient_status_id: "",
        appointment_time: "",
        patient_diseases_id: "",
        patient_diseases_child_id: "",
        next_callback_time: "",
        tags_arr: [],
      };
    },
    handleSubmit(name) {
      console.log(this.params, "params");
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.remarksloading = true;
          this.disabled = true;
          let params = JSON.parse(JSON.stringify(this.params));
          params.view_id = this.belongVIewId;
          params.move_id = this.params.move_id ? this.params.move_id : 0;
          // let paramstag = []
          // let tag = []
          // for (let item of this.params.tags_arr) {
          //     if (this.tags_arr.indexOf(item)<=-1) {
          //         let paramss = {
          //             MsgType: "ContactLabelTask",
          //             Content: {
          //                 WeChatId: item.split('()')[0],
          //                 LabelName: item.split('()')[2],
          //                 LabelId: item.split('()')[1],
          //                 AddList:  this.friendid,
          //                 taskId: new Date().getTime() + parseInt(Math.random() * 10000),
          //             },
          //         };
          //         if (this.wsIsConnect) {
          //             this.$websocket.sendSock(paramss);
          //         } else {
          //             this.$Message.error("ws未连接上");
          //         }
          //     }
          //     paramstag.push(item.split('()'))
          // }
          // for (let item of this.tags_arr) {
          //     if (this.params.tags_arr.indexOf(item)<=-1) {
          //         let paramss = {
          //             MsgType: "ContactLabelTask",
          //             Content: {
          //                 WeChatId: item.split('()')[0],
          //                 LabelName: item.split('()')[2],
          //                 LabelId: item.split('()')[1],
          //                 DelList:  this.friendid,
          //                 taskId: new Date().getTime() + parseInt(Math.random() * 10000),
          //             },
          //         };
          //         if (this.wsIsConnect) {
          //             this.$websocket.sendSock(paramss);
          //         } else {
          //             this.$Message.error("ws未连接上");
          //         }
          //     }
          //     tag.push(item.split('()'))
          // }
          // params.tags_arr = []
          // let _tags_arr = []
          // for (let item of this.tagslist) {
          //     _tags_arr.push({wechatid:item.wechatid,old_tags_id:[],tags_ids:[]})
          // }
          // for (let item of  _tags_arr) {
          //     for (let it of tag) {
          //         if (item.wechatid == it[0]) {
          //             item.old_tags_id.push(it[1])
          //         }
          //     }
          //     for (let it of paramstag) {
          //         if (item.wechatid == it[0]) {
          //             item.tags_ids.push(it[1])
          //         }
          //     }
          // }
          // let _tags_arr_ = []
          // for (let item of  _tags_arr) {
          //     if (item.old_tags_id.length != 0 && item.tags_ids.length != 0) {
          //         _tags_arr_.push(item)
          //     }
          // }
          // for (let item of _tags_arr_) {
          //     params.tags_arr.push({wechatid:item.wechatid, old_tags_id:item.old_tags_id.join(','),tags_ids:item.tags_ids.join(',')})
          // }
          // params.tags_arr = JSON.stringify(params.tags_arr)
          params.tags_arr = "";
          callbackcreate(params)
            .then((res) => {
              this.$store.commit("admin/account/changeCloseRefresh", true);
              this.$emit("changeNum");
              this.handleDrawerCancel(name);
              this.$emit("patientfuns");
              this.remarksloading = false;
              this.disabled = false;
              // 判断关闭弹窗是否刷新
            })
            .catch(() => {
              this.remarksloading = false;
              this.disabled = false;
            });
        }
      });
    },
    handleCreate(val) {
      this.logs(val);
      let params = {
        id: "",
        type: 0,
        title: val,
      };
      settingviewcreateview(params).then((res) => {
        this.$Message.success("新增常规视图成功");
        this.params.move_id = res;
        this.filterView.push({
          value: res,
          title: val,
        });
      });
    },
  },
};
</script>
<style scoped>
.time {
  font-size: 14px;
  font-weight: bold;
}

.content {
  padding: 10px 0;
}

.consultant {
  color: #9ea7b4;
}

.c-inr {
  margin: 0 10px;
}

/* h4 span {
    margin-left: 5px;
} */
.side-bg {
  background: #f2f2f2;
  padding: 24px !important;
}

.return-form {
  padding: 24px;
}

.title {
  font-weight: bold;
  font-size: 16px;
  padding: 24px 0 0 24px;
}

.sky-screen {
  margin-top: 16px;
}

.sky-s1 {
  font-size: 14px;
  margin: 0 16px;
  color: #666;
}

.sky-s2 {
  font-size: 12px;
  margin-right: 10px;
  color: #888;
}

.sky-note {
  padding: 5px 0;
}
</style>
<style>
.model .ivu-modal-body {
  padding: 0px;
}

.b-phone {
  display: flex;
  align-items: center;
}

/deep/.ivu-input-icon-validate {
  display: none !important;
}
</style>
